<style lang="less">

  @import "../less/base";

  .clients-list {
    // margin-top: 10px;
    background-color: #EFEFF4;
    // padding-top: 10px;
  }

  .grey.container.pdt {
    // padding-top: 12px;
  }

  .clientSeas {
    .pdscroll {
      background-color: #EFEFEF;
    }

    .scroll-container {
      background-color: #EFEFF4;
    }
  }
</style>

<template>
  <div class='page white-stage clientSeas'>
    <top-filter ref="topFilter" :hasSearch="isShowSearch" @item-selected="topFilterItemSelected" :filterOptions="filterOptions" @change-filter="changeFilterValue"></top-filter>
    <search-input v-if="isShowSearch" @search-change="searchChange"></search-input>
    <div class="pagination-fixer">
      <el-pagination class="filter-item mgl"
      ref="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[queryData.page_size]"
      :page-size="queryData.page_size"
      layout="sizes, prev, pager, next, jumper, total"
      :total="this.total">
      </el-pagination>
    </div>
    <div class="pdt scroll-container grey" ref="my_scroller"  
    :style="'padding-top: 92px; height:' + this.my_scrollerHeight + 'px'">
      <div class="clients-list">
        <div v-infinite-scroll="getCustoms"
        :infinite-scroll-disabled="loading"
        infinite-scroll-distance="30"
        >
          <div class="pdnormal">
            <div class="center-content-block" v-if="loading === true">
              <mt-spinner type="snake"></mt-spinner>
            </div>
            <checker v-if="batchCheck" type="checkbox" v-model="checkedClients" selected-item-class="checker-item-active">
              <checker-item class="block-item" 
              :value="toString(client.id)" 
              v-for="(client, index) in clientList">
                <clientseas-item
                  :showTeam="showTeam"
                  :batchCheck="batchCheck"
                  :canGet="canGet"
                  :onlyGet="true"
                  @on-click="onItemClick" :key="index" :client="client">
                  <div class="pull-left" v-if="batchCheck"  slot="checkerItem" >
                    <div class="batch-check-item">
                      <i class="selected-ico"></i>
                    </div>
                  </div>
                </clientseas-item>
              </checker-item>
            </checker>

            <clientseas-item
              v-for="(client, index) in clientList" 
              v-else
              :showTeam="showTeam"
              :batchCheck="batchCheck"
              :canGet="canGet"
              :onlyGet="true"
              @on-click="onItemClick" :key="index" :client="client">
              <div class="pull-left" v-if="batchCheck"  slot="checkerItem" >
                <div class="batch-check-item">
                  <i class="selected-ico"></i>
                </div>
              </div>
            </clientseas-item>
          </div>
        </div>
      </div>
    </div>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="showBtns && loginUser.is_team_manager && !batchCheck && !show" @click="batchCheck=true">批量分配</button>
    <button class="fixed-bt-btn fixed-btr2-btn" v-if="batchCheck" @click="selectAll">全选</button>
    <button class="fixed-bt-btn fixed-btr1-btn" v-if="batchCheck" @click="batchCheck=false">取消</button>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="showBtns && batchCheck" @click="distributeTrigger">分配</button>
    <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <crm-tabbar ref="tabbar" :activeItem='activeItem' v-if="activated"></crm-tabbar>

    <distribute-client
    :isShow="show"
    @on-cancel="show=false"
    :deliverTeamOpts="deliverTeamOpts"
    @on-confirm="memberSelect" />

    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
    <confirm v-model="showDistributeConfirm"
        title="温馨提示"
        @on-confirm="onDistributeConfirm">
      <p style="text-align:center;">你确定要分配客户给此成员吗?</p>
    </confirm>
    <!-- <popup-picker :showMask="showMask" :value="checkValues" :show="confirmAssignShow" :show-cell="false" title="TEST"  :columns="1" :data="teamsMembers" v-model="selectedCounselor" @on-hide="confirmDistribute"></popup-picker> -->
  </div>
</template>

<script>

import crmTabbar from '../components/crm-tabbar'
import crmCover from '../components/crm-cover'
import topFilter from '../components/top-filter'
import teamMemberItem from '../components/team-member-item'
import clientseasItem from '../components/clientseas-item'
import DistributeClient from '../components/distribute-client'
import SearchInput from '../components/SearchInput'

// import my_scroller from 'vue-my_scroller'
// import {Popup, XDialog} from 'vux'
import XDialog from 'vux/src/components/x-dialog'
import Popup from 'vux/src/components/popup'
import PopupPicker from 'vux/src/components/popup-picker'

import {showDialog, hideDialog} from '../lib/dialog'

import store from '../store'
import { getTopFilterOptions, topFilterOptions } from '../lib/options/clientSeas'
import { Checker, CheckerItem } from 'vux/src/components/checker'
import Confirm from 'vux/src/components/confirm'

// 按需引入加载mint-ui更多插件
import 'mint-ui/lib/loadmore/style.css'
import 'mint-ui/lib/spinner/style.css'
import 'mint-ui/lib/infinite-scroll/style.css'
import {Loadmore, Spinner} from 'mint-ui'

var zepto = require('npm-zepto')

import { mapState, mapActions } from 'vuex'
import  { mapField } from '../lib/backend'

import  { Pagination } from 'element-ui'

const INTEL_CLIENT_SEA = 'intel-client-seas'
const NORMAL_CLIENT_SEA = 'normal-client-seas'

import Q from 'q'

export default {
  props: {
    showBtns: {
      default: true
    }
  },
  data () {
    let overHeight = document.body.scrollHeight + 10
    return {
      activated: true,
      teams: [],
      activeItem: '',
      isMore: false,
      showTeam: true,
      isMoreTeam: false,
      my_scrollerHeight: '',
      existTeamsIDs: [],
      my_scrollerTop: '',
      winHeight: '',
      loading: false,
      memberLoading: false,
      hasMoreData: true,
      team_page_size: 100,
      memberHasMoreData: true,
      containerHeight: 'height:' + overHeight + 'px;',
      page_size: 15,
      page_index: 1,
      showDistributeConfirm: false,
      isShowSearch: false,
      distributedClients: [],
      currentPage: 1,
      total: 0,
      team_page_index: 1,
      custom_type: 0,
      checkedClients: '',
      deliverTeamOpts: [],
      confirmAssignShow: false,
      selectedCounselor: false,
      batchCheck: false,
      show: false,
      keyword: '',
      checkValues: [],
      cleanClientList: {},
      clientList: [],
      teamFilterOptions: [],
      teamsMembers: [],
      selectedClientId: null,
      noDataText: '',
      tnoDataText: '',
      originNoDataText: '暂无数据',
      showMask: false,
      demo21: null,
      filterData: { // 初始化的筛选数据
      },
      filterOptions: {},
      loadStatus: '',
      total: 0,
      canGet: false,
      queryData: {
        page_index: 1,
        page_size: 10
      }
    }
  },

  components: {
    crmTabbar,
    crmCover,
    topFilter,
    clientseasItem,
    Popup,
    teamMemberItem,
    // my_scroller,
    SearchInput,
    XDialog,
    PopupPicker,
    Checker,
    CheckerItem,
    Confirm,
    DistributeClient,
    [Pagination.name]: Pagination,
    [Loadmore.name]: Loadmore,
    [Spinner.name]: Spinner
  },

  activated () {
    if (this.position) {
      this.$refs.my_scroller.scrollTop = this.position.top
    }
    let scroller = this.$refs.my_scroller

    zepto(scroller).unbind('scroll.' + this.custom_type)
      .on('scroll.' + this.custom_type, () => {
        let scrollTop = this.$refs.my_scroller.scrollTop
        this.position = {top: scrollTop}
      })
     this.activated = true
   },
  deactivated () {
   this.activated = false
   console.log('this.position', this.position)
  },

  watch: {
    clientList () {
      this.cleanClientList = {}
      this.clientList.forEach((elem, index) => {
        this.cleanClientList[elem.id] = elem
      })
    },

    checkedClients (checkedClients) {
      console.debug('checkedClients', JSON.stringify(checkedClients))
      this.selectedClientId = checkedClients
    },

    batchCheck (value) {
      console.debug(value, 'batchCheck')
      if (value === true) {

      } else {
        this.checkedClients = []
      }
    },
    show (val) {
      if (val === false) {
        this.selectedClientId = ''
      }
    }
  },

  methods: {
    distributeTrigger () {
      this.show = true
      this.initDistributeTeamOpts()
    },
    initDistributeTeamOpts () {
      const data = this.$refs.topFilter.getData()
      const myTeamList = this.loginUser.my_team_list
      const myTeamManangeList = this.loginUser.teams
      console.log(this.loginUser)

      let deliverTeamOpts = []
      let is_manage = false
      if (data.team_id && ! this.loginUser.is_manager) {
        for (const teamId in myTeamManangeList) {
          deliverTeamOpts.push({
            key: myTeamManangeList[teamId].team_id,
            value: myTeamManangeList[teamId].team_name
          })
          if (data.team_id == myTeamManangeList[teamId].team_id) {
            is_manage = true
          }
        }
        if (! is_manage) {
          this.show = false;
          this.batchCheck = false
          showDialog('你不是当前团队管理员');
          return false
        }

//        deliverTeamOpts = [
//          {
//            key: data.team_id,
//            value: myTeamList[data.team_id]
//          }
//        ]
      } else {
//        for (const teamId in myTeamManangeList) {
//          deliverTeamOpts.push({
//            key: myTeamManangeList[teamId].team_id,
//            value: myTeamManangeList[teamId].team_name
//          })
//        }
        for (const teamId in myTeamList) {
          deliverTeamOpts.push({
            key: teamId,
            value: myTeamList[teamId]
          })
        }
      }
      this.deliverTeamOpts = deliverTeamOpts
    },
    selectAll () {
      const list = []
      this.clientList.forEach((client, index) => {
        list.push(client.id + '')
      })
      this.checkedClients = list
    },
    getScrollTop (element) {
      if (element === window) {
        return Math.max(window.pageYOffset || 0, document.documentElement.scrollTop);
      }
      return element.scrollTop;
    },
    caculatemy_scroller () {
      const winHeight = window.innerHeight
      const filterHeight = this.$refs['topFilter'].$el.offsetHeight
      const tabbarHeight = this.$refs['tabbar'].$el.offsetHeight
      this.winHeight = window.innerHeight
      this.my_scrollerTop = filterHeight
      this.my_scrollerHeight = winHeight - filterHeight - tabbarHeight - 50
    },
    handleSizeChange () {
    },
    handleCurrentChange (val) {
      this.queryData = {
        ...this.queryData,
        page_index: val
      }
      this.currentPage = val
      console.log('val', val, this.currentPage)
      this.getCustoms()
    },
    initPageFilters (pageData) {
      const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
      const filters = []
      for (let i = 1; i <= totalPage; i++) {
        filters.push({
          value: i,
          text: i
        })
      }
      this.filters = filters
    },
    showConfirmDialog (member) {
      this.selectedMember = member
      this.showDistributeConfirm = true
    },
    onDistributeConfirm () {
      this.memberSelect(this.selectedMember)
    },
    getTopFilterOptions: getTopFilterOptions,
    confirmDistribute (value) {
      if (value === true) {

      }
      this.batchCheck = false
    },
    toString (id) {
      return id + ''
    },
    filterClient (client) {
      return {
        value: client.id,
        key: client.id
      }
    },
    batchCheckSelected () {
      if (this.batchCheck === true) {
        // this.selectedClientId =
      }
    },
    refresh (iscroll) {
      console.log('refresh')
      this.loadStatus = 'refresh'
      this.getCustoms({ page_index: 1 })
    },

    hideDialog () {
      hideDialog()
      this.emptyCustoms()
      this.getCustoms()
    },
    log () {
      console.log('ee')
    },

    load (iscroll) {
      console.log('load')
      this.loadStatus = 'load'
      this.getCustoms()
      // Load new data
    },

    refreshMember (iscroll) {
      console.log('refreshMember')
      this.loadMembers()
    },

    logMember () {
      console.log('logMember')
    },

    loadMember (iscroll) {
      console.log('loadMember')
      this.loadMembers()
      // Load new data
    },

    searchChange (value) {
      if (!value) return
      if (typeof this.sid !== 'undefined') {
        clearTimeout(this.sid)
      }

      this.sid = setTimeout(() => {
        if (!this.originClientList) {
          this.originClientList = this.clientList
        }
        this.emptyCustoms()
        this.keyword = value
        this.getCustoms()
      }, 1000)
    },

    hidePopup () {
      showDialog('你取消了分配！')
      setTimeout(() => {
        hideDialog()
      }, 2500)
      this.show = false
      console.log('hidePopup')
    },

    test () {
      console.log('test')
    },

    onItemClick (clientID) {
      // this.teamsMembers = []
      this.loadMembers()
      this.initDistributeTeamOpts()
      this.show = true
      this.selectedClientId = clientID
      console.log('clientID: ', clientID)
    },

    topFilterItemSelected (item, index) {
      console.log('topFilterItemSelected')

      if (typeof item.name !== 'undefined' && item.name === 'search') {
        this.isShowSearch = !this.isShowSearch // 搜索栏打开
      } else {
        this.isShowSearch = false // 打开的是筛选栏
      }

      if (this.isShowSearch === false && this.keyword) {
        if (this.isShowSearch === false) {
          this.keyword = ''
          this.emptyCustoms()
          this.getCustoms()
        }
      }
    },
    mergeClientList (data) {
      if (!this.clientIDs) this.clientIDs = []
      let newClients = []

      data.forEach((client, index) => {
        console.log(this.clientIDs.indexOf(client.id), 'this.clientIDs.indexOf(client.id)')
        if (this.clientIDs.indexOf(client.id) === -1) {
          newClients.push(client)
          this.clientIDs.push(client.id)
        }
      })
      if (this.loadStatus === 'refresh') {
        this.clientList = newClients.concat(this.clientList)
      } else {
        this.clientList = this.clientList.concat(newClients)
      }
    },
    memberSelect (member) {
      if (!this.selectedClientId) {
        showDialog('您必须选择至少一个客户!')
        return
      }

      let info = {
        target_suid: member.suid,
        custom_id: this.selectedClientId,
        target_team_id: member.team_id,
        distribute_type: 'GH#',
        opt_type: 'TPT'
      }

      let that = this
      this.$vux.loading.show({
        text: '加载中...'
      })
      store.dispatch('distribute', info).then((response) => {
        if (response.data.errcode === 0) {
          showDialog('您将客户分配给成员：' + member.name)
          setTimeout(() => {
            hideDialog()
          }, 2500)
          that.show = false
          this.batchCheck = false
          this.clientList = this.clientList.filter(client => client.id !== info.custom_id)
        } else {
          showDialog(response.data.errmsg)
          setTimeout(() => {
            hideDialog()
          }, 2500)
        }
        this.$vux.loading.hide()
      }).catch((error) => {
        console.log(error)
        showDialog('系统出错！请报告管理员')
        setTimeout(() => {
          hideDialog()
        }, 2500)
        this.$vux.loading.hide()
      })
    },
    getCustoms (data) {
      let defaultData = {...this.queryData}
      let that = this
      let id = Math.random()
      this.id = id

      if (this.loading === true || this.hasMoreData === false) return
      this.loading = true
      
      defaultData['custom_type'] = this.custom_type

      if (this.keyword) defaultData['keyword'] = this.keyword
      data = Object.assign(defaultData, mapField(this.filterData, {
        team_id: 'team_id',
        insert_time: 'insert_time',
        order_by: 'order_by',
      }), data)
      this.noDataText = '数据加载中...'

      let method = ''
      if (this.type === NORMAL_CLIENT_SEA) {
        method = 'getClientSeasCustoms'
      } else if (this.type === INTEL_CLIENT_SEA ){
        method = 'getIntelClientSeaCustoms'
      }
      console.log(method, 'method', this.type)

      method && this[method](data).then((response) => {
        if (id !== this.id) return
        this.endLoading()
        let resData = response.data
        if (response.data.errcode === 0) {
          if (this.total != resData.results.total) this.initPageFilters(resData.results)
          this.total = resData.results.total
          this.clientList = resData.results.data
        } else {
          console.debug('系统服务异常！请联系管理员!', response.data.errmsg)
        }
        this.init = true
        this.$nextTick(() => this.loading = false)
      }).catch((error) => {
        this.endLoading()
        this.loading = false
        this.hasMoreData = false
        console.log(error)
      })
    },
    endLoading () {
      // setTimeout(() => {
      //   if (this.$refs.my_scroller) {
      //     this.$refs.my_scroller.finishInfinite(true)
      //     this.$refs.my_scroller.finishPullToRefresh()
      //   }
      // }, 300)
    },
    initBatchCheck () {
      if (!this.showBtns) return 
      
      let that = this
      let items = [
        {
          'id': 'batchCheck', // 字符串
          'text': '批量分配'
        }
      ]
      const dd = window['dd']
      // dd.biz.navigation.setMenu({
      //   backgroundColor: '#FFFFFF',
      //   textColor: '#0089cd',
      //   items: items,
      //   onSuccess: function (data) {
      //     if (that.batchCheck !== true) {
      //       that.batchCheck = true
      //     }
      //   },
      //   onFail: function () { }
      // })
    },

    emptyCustoms () {
      this.clientList = []
      this.clientIDs = []
      this.page_index = 1
      this.hasMoreData = true
      this.loading = false
    },
    resetCustoms () {
      this.clientList = this.originClientList
    },

    loadMembers (data) {
      return Q.promise((resolve, reject) => {
        let that = this
        let params = {
          page_index: this.team_page_index,
          page_size: this.team_page_size,
          is_own: 1,
          source: 'webapp'
        }
        if (this.teamLoading === true || this.memberHasMoreData === false) return
        this.teamLoading = true
        params = Object.assign(params, data)
        store.dispatch('getTeams', params).then((response) => {
          this.teamLoading = false
          const totalPage = Math.ceil(parseInt(response.data.results.total) / parseInt(this.team_page_size))
          this.memberHasMoreData = this.team_page_index < totalPage

          setTimeout(() => {
            if (typeof response.data.results.teams !== 'undefined') {
              this.teams = this.teams.concat(response.data.results.teams || [])
              that.filterUserFromTeam(this.teams)
              resolve(true)
            } else {
              console.warn('无团队')
            }
            this.endTeamLoading()
            that.team_page_index++
          }, 800)
        }).catch((e) => {
          console.log(e)
          this.teamLoading = false
          this.memberHasMoreData = false
          this.endTeamLoading()
        })
      })
    },
    // 从接口中筛选出团队信息
    filterUserFromTeam (teams) {
      let temps = []
      if (!this.existTeamsIDs) this.existTeamsIDs = []
      teams.forEach((team, index) => {
        let isSelfTeam = false
        console.warn('team', team, 'index', index)

        // team.team_managers.forEach((member, mindex) => {
        //   if(member.suid === this.loginUser.id) {
        //     isSelfTeam  = true
        //   }
        // });

        if (team.id === this.loginUser.teams[0].team_id) isSelfTeam = true

        // if (isSelfTeam === true) {
          if (team.team_managers) {
            team.team_managers.forEach((member, mindex) => {
              let gid = member.suid
              if (this.existTeamsIDs.indexOf(gid) === -1) {
                member.team_name = team.team_name
                member.name = member.name
                member.value = member.suid
                member.parent = 0
                temps.push(member)
                this.existTeamsIDs.push(gid)
              }
            })
          }

          if (team.team_members) {
            team.team_members.forEach((member, mindex) => {
              let gid = member.suid
              if (this.existTeamsIDs.indexOf(gid) === -1) {
                member.team_name = team.team_name
                member.name = member.name
                member.value = member.suid
                member.parent = 0
                temps.push(member)
                this.existTeamsIDs.push(gid)
              }
            })
          }
        // }
      })
      console.log(temps)
      this.teamsMembers = this.teamsMembers.concat(temps)
    },
    endTeamLoading () {
      let that = this
      setTimeout(() => {
        if (that.$refs.team_my_scroller) {
          that.$refs.team_my_scroller.finishInfinite(true)
          that.$refs.team_my_scroller.finishPullToRefresh()
          if (that.teamsMembers.length > 0) {
            that.tnoDataText = ''
          }
        }
      }, 1000)
    },
    // 筛选器
    changeFilterValue (filterOptions) {
      var submitData = Object.assign({}, this.filterData)
      console.debug('clientseas', JSON.stringify(filterOptions))
      filterOptions.forEach((object, index) => {
        if (object.options) {
          object.options.forEach((secObject, secIndex) => {
            if (secObject.value === object.checked) {
              if (secObject.options) {
                secObject.options.forEach((rdObj, rdIndex) => {
                  if (secObject.checked === rdObj.value) {
                    submitData[secObject.name] = rdObj.value
                  }
                })
              } else {
                submitData[object.name] = object.checked
              }
            }
          })
        }
      })
      let originalFilterData = this.filterData
      if (!this.isSameObj(originalFilterData, submitData)) {
        this.filterData = submitData
        this.emptyCustoms()
        this.getCustoms()
//        this.initDistributeTeamOpts()
      }
    },

    isSameObj (obj1, obj2) {
      return JSON.stringify(obj1) === JSON.stringify(obj2)
    },

    resetClients () {
      this.clientList = []
    },
    handlePopup (status) {
      this.team_page_index = 1
      if (status === 'show') {
        // setTimeout(() => {
        //   if(this.$refs.team_my_scroller) {
        //     this.$refs.team_my_scroller.resize()
        //   }
        // },200)
      } else {
        // this.existTeamsIDs = []
      }
    },
    ...mapActions({
      getIntelClientSeaCustoms: 'getIntelClientSeaCustoms',
      getClientSeasCustoms: 'getClientSeasCustoms'
    })
  },

  computed: {
    ...mapState({
      isShowCover: state => state.app.isShowCover,
      loginUser: state => state.app.user,
      isAppMode: state => state.config.isAppMode,
      type: state => state.route.name
    })
  },

  beforeMount () {
    store.dispatch('getCustomSource')
    if (this.$route.query.custom_type === '0') {
      this.filterOptions = topFilterOptions
    } else {
      this.filterOptions = this.getTopFilterOptions(this.loginUser.my_team_list)
    }

    this.$nextTick(() => {
      this.filterData = this.$refs.topFilter.getData()
    })
  },
  mounted () {
    this.caculatemy_scroller()

    if (this.loginUser.is_team_manager) {
      this.loadMembers().then((status) => {
        if (status === true) {
          this.initBatchCheck()
          this.team_page_index ++
        }
      })
    }

    let query = this.$route.query

    this.custom_type = query.custom_type
    this.activeItem = query.activeItem

    this.filterOptions = this.filterOptions
    this.teamFilterOptions = this.filterOptions

    this.noDataText = this.originNoDataText
    this.tnoDataText = this.originNoDataText

    this.callJsApi('biz.navigation.setTitle', {
      title: '客户公海'
    })
  }
}

</script>
